﻿using Newtonsoft.Json;
using BaoShouTangServer.ApiModels;
using BaoShouTangServer.ApiServies;
using BaoShouTangServer.DTOModel;
using BaoShouTangServer.Models;
using BaoShouTangServer.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using U8Login;

namespace BaoShouTangServer.Controllers
{
    public class PU_ArrivalVouchController : Controller
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // GET: PU_ArrivalVouch
        [HttpGet]
        public JsonResult Index()
        {
            string resp = "";
            string msg = "";
            clsLogin clsLogin = LogInService.GetLogin(ref resp, ref msg);
            return Json(new { resp = resp, message = $"{msg}" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Add(List<z_采购质检申请单体> z_质检申请单体List)
        {
            Logger.Warn("接受到的z_采购质检申请单体：" + JsonConvert.SerializeObject(z_质检申请单体List));

            string resp = "";
            string msg = "";
            string responseMsg = "";
            HttpData<object> httpData = new HttpData<object>();

            foreach (var item in z_质检申请单体List)
            {
                z_采购质检申请单体 z_质检申请单体 = SqlSugarHelp.scope.Queryable<z_采购质检申请单体>().Where(it => it.bguid == item.bguid).First();
                DTOPO_Pomain dtoPO_Pomain = new DTOPO_Pomain();
                dtoPO_Pomain.cUser_Name = z_质检申请单体.质检人;
                dtoPO_Pomain.POID = z_质检申请单体.POID.Value;
                dtoPO_Pomain.入库日期 = z_质检申请单体.入库日期.GetValueOrDefault();
                dtoPO_Pomain.dtoPO_Podetails = new List<DTOPO_Podetails>();

                DTOPO_Podetails dTOPO_Podetails = new DTOPO_Podetails();
                dTOPO_Podetails.ID = z_质检申请单体.ID.Value;
                dTOPO_Podetails.qualifiedQuantity = z_质检申请单体.入库数量.Value;
                dTOPO_Podetails.cbatch = z_质检申请单体.炉批号;
                dTOPO_Podetails.到货单备注 = z_质检申请单体.到货单备注;


                dtoPO_Pomain.dtoPO_Podetails.Add(dTOPO_Podetails);

                string 到货单接口返回result = "";


                clsLogin clsLogin = LogInService.GetLogin(ref resp, ref msg);
                if (resp != "登陆成功")
                {
                    return Json(new { success = false, message = $"{msg}" });
                }
                //查采购单头
                PO_Pomain pO_Pomain = SqlSugarHelp.scope.Queryable<PO_Pomain>().Where(it => it.POID == dtoPO_Pomain.POID).First();
                //查采购单行
                List<int> ids = dtoPO_Pomain.dtoPO_Podetails.Select(it => it.ID).ToList();
                List<PO_Podetails> pO_Podetails = SqlSugarHelp.scope.Queryable<PO_Podetails>()
                                                                .Where(it => it.POID == dtoPO_Pomain.POID && ids.Contains(it.ID))
                                                                .ToList();
                //生成到货单
                string ID = PU_ArrivalVouchService.生成采购到货(clsLogin, dtoPO_Pomain, pO_Pomain, ref 到货单接口返回result);
                if (string.IsNullOrEmpty(到货单接口返回result) == true)
                {

                    int id = int.Parse(ID);
                    pu_ArrHead pu_ArrHead = SqlSugarHelp.scope.Queryable<pu_ArrHead>().Where(it => it.id == id).First();
                    List<pu_arrbody> pu_ArrbodyList = SqlSugarHelp.scope.Queryable<pu_arrbody>().Where(it => it.id == id).ToList();
                    //修改批次号
                    //if (pu_ArrbodyList != null && pu_ArrbodyList.Count > 0)
                    //{
                    //    foreach (var pu_Arrbody in pu_ArrbodyList)
                    //    {
                    //        if (string.IsNullOrEmpty(pu_Arrbody.cbatch) == false)
                    //        {
                    //            pu_Arrbody.cbatch = pu_ArrHead.ccode +" "+ pu_Arrbody.cbatch;
                    //        }

                    //    }

                    //    int r = SqlSugarHelp.scope.Updateable(pu_ArrbodyList).UpdateColumns(it => new { it.cbatch }).WhereColumns(it => it.autoid).ExecuteCommand();
                    //}

                    item.U8入库id = ID;
                    item.U8入库单号 = pu_ArrHead.ccode;
                    item.U8入库结果 = "入库成功";
                    item.U8入库数量 = SqlSugarHelp.scope.Queryable<pu_arrbody>().Where(it => it.id == id).First().fvalidquantity;

                    //responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单成功。到货单号：{pu_ArrHead.ccode}";

                    //生成成功，进行审核
                    //PU_ArrivalVouchService.审核到货单审核(clsLogin, ID, ref msg);
                    if (string.IsNullOrEmpty(msg) == true)
                    {
                        responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单成功。到货单号：{pu_ArrHead.ccode},审核成功" + "\r\n";
                    }
                    else
                    {
                        responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单成功。到货单号：{pu_ArrHead.ccode},到货单审核失败：{msg}" + "\r\n";
                    }

                }
                else
                {
                    item.U8入库结果 = "入库失败";
                    responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单失败，失败原因:{到货单接口返回result}" + "\r\n";
                }

                SqlSugarHelp.scope.Updateable(item)
                            .UpdateColumns(it => new { it.U8入库id, it.U8入库结果, it.U8入库单号, it.U8入库数量 })
                            .ExecuteCommand();
            }
            Logger.Warn("生成U8的的z_采购质检申请单体：" + responseMsg);
            httpData.msg = responseMsg;
            return Json(httpData);
        }

        public JsonResult AddList(List<z_采购质检申请单体> z_质检申请单体List)
        {
            Logger.Warn("AddList接受到的z_采购质检申请单体：" + JsonConvert.SerializeObject(z_质检申请单体List));

            string resp = "";
            string msg = "";
            string responseMsg = "";
            HttpData<object> httpData = new HttpData<object>();

            //如果多于一个供应商，就返回提示报错
            if (z_质检申请单体List.Select(it => it.供应商名称).Distinct().Count() > 1)
            {
                string ms = string.Join(";", z_质检申请单体List.Select(it => it.供应商名称).ToList());
                httpData.msg = $"多个供应商[{ms}]不能同时生成到货单";
                return Json(httpData);
            }
            //如果多于一个采购单，就返回提示报错
            if (z_质检申请单体List.Select(it => it.采购订单号).Distinct().Count() > 1)
            {
                string ms = string.Join(";", z_质检申请单体List.Select(it => it.采购订单号).ToList());
                httpData.msg = $"多个采购单[{ms}]不能同时生成到货单";
                return Json(httpData);
            }

            z_采购质检申请单体 z_质检申请单体 = z_质检申请单体List.First();
            DTOPO_Pomain dtoPO_Pomain = new DTOPO_Pomain();
            dtoPO_Pomain.cUser_Name = z_质检申请单体.质检人;
            dtoPO_Pomain.POID = z_质检申请单体.POID.Value;
            dtoPO_Pomain.入库日期 = z_质检申请单体.入库日期.GetValueOrDefault();
            dtoPO_Pomain.dtoPO_Podetails = new List<DTOPO_Podetails>();

            foreach (var item in z_质检申请单体List)
            {
                DTOPO_Podetails dTOPO_Podetails = new DTOPO_Podetails();
                dTOPO_Podetails.ID = item.ID.Value;
                dTOPO_Podetails.qualifiedQuantity = item.入库数量.Value;
                dTOPO_Podetails.cbatch = z_质检申请单体.炉批号;
                dTOPO_Podetails.到货单备注 = z_质检申请单体.到货单备注;
                dtoPO_Pomain.dtoPO_Podetails.Add(dTOPO_Podetails);
            }

           

            string 到货单接口返回result = "";


            clsLogin clsLogin = LogInService.GetLogin(ref resp, ref msg);
            if (resp != "登陆成功")
            {
                return Json(new { success = false, message = $"{msg}" });
            }
            //查采购单头
            PO_Pomain pO_Pomain = SqlSugarHelp.scope.Queryable<PO_Pomain>().Where(it => it.POID == dtoPO_Pomain.POID).First();
            //查采购单行
            List<int> ids = dtoPO_Pomain.dtoPO_Podetails.Select(it => it.ID).ToList();
            //List<PO_Podetails> pO_Podetails = SqlSugarHelp.scope.Queryable<PO_Podetails>()
            //                                                .Where(it => it.POID == dtoPO_Pomain.POID && ids.Contains(it.ID))
            //                                                .ToList();
            //生成到货单
            string ID = PU_ArrivalVouchService.生成采购到货(clsLogin, dtoPO_Pomain, pO_Pomain, ref 到货单接口返回result);
            if (string.IsNullOrEmpty(到货单接口返回result) == true)
            {

                int id = int.Parse(ID);
                pu_ArrHead pu_ArrHead = SqlSugarHelp.scope.Queryable<pu_ArrHead>().Where(it => it.id == id).First();
                List<pu_arrbody> pu_ArrbodyList = SqlSugarHelp.scope.Queryable<pu_arrbody>().Where(it => it.id == id).ToList();
                //修改批次号
                //if (pu_ArrbodyList != null && pu_ArrbodyList.Count > 0)
                //{
                //    foreach (var pu_Arrbody in pu_ArrbodyList)
                //    {
                //        if (string.IsNullOrEmpty(pu_Arrbody.cbatch) == false)
                //        {
                //            pu_Arrbody.cbatch = pu_ArrHead.ccode + " " + pu_Arrbody.cbatch;
                //        }
                       
                //    }

                //    int r = SqlSugarHelp.scope.Updateable(pu_ArrbodyList).UpdateColumns(it => new { it.cbatch }).WhereColumns(it => it.autoid).ExecuteCommand();
                //}

                foreach (var item in z_质检申请单体List)
                {
                    item.U8入库id = ID;
                    item.U8入库单号 = pu_ArrHead.ccode;
                    item.U8入库结果 = "入库成功";
                    item.U8入库数量 = SqlSugarHelp.scope.Queryable<pu_arrbody>().Where(it => it.id == id && it.iposid == item.ID).First().fvalidquantity;
                }

                //responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单成功。到货单号：{pu_ArrHead.ccode}";

                //生成成功，进行审核
               // PU_ArrivalVouchService.审核到货单审核(clsLogin, ID, ref msg);
                if (string.IsNullOrEmpty(msg) == true)
                {
                    responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单成功。到货单号：{pu_ArrHead.ccode},审核成功" + "\r\n";
                }
                else
                {
                    responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单成功。到货单号：{pu_ArrHead.ccode},U8到货单审核失败：{msg}" + "\r\n";
                }

            }
            else
            {
                foreach (var item in z_质检申请单体List)
                {
                    item.U8入库结果 = "入库失败";
                }
                responseMsg += $"采购单号{pO_Pomain.cPOID}的生成到货单失败，U8失败原因:{到货单接口返回result}" + "\r\n";
            }

            SqlSugarHelp.scope.Updateable(z_质检申请单体List)
                        .UpdateColumns(it => new { it.U8入库id, it.U8入库结果, it.U8入库单号, it.U8入库数量 })
                        .ExecuteCommand();

            Logger.Warn("生成U8的的z_采购质检申请单体：" + responseMsg);
            httpData.msg = responseMsg;
            return Json(httpData);
        }


        public JsonResult CancelconfirmArr(string code)
        {
            HttpData<object> httpData = new HttpData<object>();
            pu_ArrHead pu_ArrHead = SqlSugarHelp.scope.Queryable<pu_ArrHead>().Where(it => it.ccode == code).First();
            if (pu_ArrHead == null)
            {
                return Json(new { success = false, message = $"未查到到货单{code}" });
            }
            string resp = "";
            string msg = "";
            string responseMsg = "";
            clsLogin clsLogin = LogInService.GetLogin(ref resp, ref msg);
            if (resp != "登陆成功")
            {
                return Json(new { success = false, message = $"{msg}" });
            }
           
            PU_ArrivalVouchService.弃审到货单(clsLogin, pu_ArrHead?.id.ToString(), ref msg);
            if (string.IsNullOrEmpty(msg) == true)
            {
                responseMsg += $"到货单号：{pu_ArrHead.ccode},弃审成功" + "\r\n";
            }
            else
            {
                responseMsg += $"到货单号：{pu_ArrHead.ccode}弃审失败：{msg}" + "\r\n";
            }
            httpData.msg = responseMsg;
            return Json(httpData);
        }
    }
}